<template>
  <div class="page">
    <du-nav-bar title="sessionStorage-测试1" url="/"></du-nav-bar>
    <div class="page-box">
      <div>
        <van-button type="primary" class="m-r-10" @click="addStorage">add / reset</van-button>
        <van-button type="primary" class="m-r-10" @click="editStorage">edit</van-button>
        <van-button type="primary" @click="deleteStorage">delete</van-button>
      </div>

      <div>{{ mystorage?.a }}</div>
      <div>{{ mystorage?.b?.name }}</div>
    </div>
  </div>
</template>

<script setup>
import { useStorage } from '@vueuse/core'

let mystorage = ref(null)

// 初始化
if (sessionStorage.getItem('my-storage')) {
  // 如果session已经有值了
  mystorage.value = useStorage('my-storage', {}, sessionStorage).value
}

// 添加/重置
const addStorage = () => {
  deleteStorage()
  const person = {
    a: 1,
    b: {
      name: '张三',
      age: 12,
    },
  }
  mystorage.value = useStorage('my-storage', person, sessionStorage).value
}
// 修改
const editStorage = () => {
  if (mystorage.value) {
    mystorage.value.a += 1
    mystorage.value.b.name += 1
  }
}
// 删除
const deleteStorage = () => {
  sessionStorage.removeItem('my-storage')
  mystorage.value = null // 注意要把mystorage.value清掉!!!!!
}
</script>

<style scoped lang="scss">
.page-box {
  padding: 10px;
}
.m-r-10 {
  margin-right: 10px;
}
</style>
